<template>
	<view class="contianer">
		<top-bar>
			<template #left>
				<image src="../../static/images/login/back.png" @tap="back" style="width: 44rpx;height: 44rpx;"></image>
			</template>
			<template #center>
				<text style="font-size: 40rpx;">个人简介</text>
			</template>
			<template #right>
				<view style="width: 60rpx;">
				</view>
			</template>
		</top-bar>
		<view class="main">
			<view class="img">
				<view class="title">头像</view>
				<view class="img_img" @tap="isMaster()&&upload()">
					<!-- &&第一个为假则不执行后面，第一个如果为真则执行后面的逻辑 -->
					<image :src="cropFilePath" @tap.stop="preview()" class="img_image"></image>
					<!-- <previewImg ref="previewImage" :imgs="[cropFilePath]" ></previewImg> -->
					<!-- <image class="img_image" src="../../static/img/two.png" mode=""></image> -->
				</view>
				<image-cropper :src="tempFilePath" @confirm="confirm" @cancel="cancel"></image-cropper>
				<view class="edit">
					<image src="../../static/images/login/back.png" mode=""></image>
				</view>
			</view>
			<view class="text">
				<view class="text_title">昵称</view>
				<view class="text_content" @tap.stop="dataInteraction('name')">
					{{userDetail.name}}
				</view>
				<view class="text_edit">
					<image src="../../static/images/login/back.png" mode=""></image>
				</view>
			</view>
			<view class="text">
				<view class="text_title">签名</view>
				<view class="text_content" @tap.stop="dataInteraction('explain')">
					{{userDetail.explain}}
				</view>
				<view class="text_edit">
					<image src="../../static/images/login/back.png" mode=""></image>
				</view>
			</view>
			<view class="text">
				<view class="text_title">注册</view>
				<view class="text_content">
					{{userDetail.time}}
				</view>
				<view class="text_edit">
				</view>
			</view>
			<view class="text">
				<view class="text_title">性别</view>
				<view class="text_content">
					<view class="uni-list">
						<view class="uni-list-cell">
							<view class="uni-list-cell-db">
								<picker :disabled="!isMaster()" @change="bindPickerChange" :value="index"
									:range="sexOption">
									<!-- 点击得到value，将value设置给index，显示数据 -->
									<view class="uni-input">{{sexOption[index]}}</view>
								</picker>
							</view>
						</view>
					</view>
				</view>
				<view class="text_edit">
					<image src="../../static/images/login/back.png" mode=""></image>
				</view>
			</view>
			<view class="text">
				<view class="text_title">生日</view>
				<view class="text_content">
					<view class="uni-list">
						<view class="uni-list-cell">
							<view class="uni-list-cell-left">
							</view>
							<view class="uni-list-cell-db">
								<!-- false表示开启，true表示关闭 -->
								<picker mode="date" :disabled="!isMaster()" :value=date :start="startDate"
									:end="endDate" @change="bindDateChange">
									<view class="uni-input">{{date}}</view>
								</picker>
							</view>
						</view>
					</view>
				</view>
				<view class="text_edit">
					<image src="../../static/images/login/back.png" mode=""></image>
				</view>
			</view>
			<view class="text">
				<view class="text_title">电话</view>
				<view class="text_content" @tap.stop="dataInteraction('phone')">
					{{userDetail.phone}}
				</view>
				<view class="text_edit">
					<image src="../../static/images/login/back.png" mode=""></image>
				</view>
			</view>
			<view class="text">
				<view class="text_title">邮箱</view>
				<view class="text_content" @tap.stop="dataInteraction('email')">
					{{userDetail.email}}
				</view>
				<view class="text_edit">
					<image src="../../static/images/login/back.png" mode=""></image>
				</view>
			</view>
			<view class="text" v-if="isMaster()">
				<view class="text_title">密码</view>
				<view class="text_content" @tap.stop="dataInteraction('pwd')">
					*******
				</view>
				<view class="text_edit">
					<image src="../../static/images/login/back.png" mode=""></image>
				</view>
			</view>
			<!-- 这里需要判断 好友的详情不需要展示这个退出应用 -->
			<view class="exit" v-if="isMaster()">
				<view class="exit_txt" @click="loginOut($event)">
					退出应用
				</view>
			</view>
			<!-- 如果不是好友也不是本人，这里的内容就要删除 -->
			<view class="exit" v-if="!isMaster()&&isfriend">
				<view class="exit_txt" @click="delFriens(userDetail.id)">
					删除好友
				</view>
			</view>
		</view>
		<view class="modify" v-show="isModify">
			<view class="fiexd" style="position: relative;height: 100%;">
				<view style="height: 65%;" @tap="cancelEdit"></view>
				<view class="cover" :animation="coverAnimationTemp">
					<view class="modify-top-bar">
						<view class="one" @tap.stop="cancelEdit">取消</view>
						<view class="two" @tap="submit()">确定</view>
					</view>
					<view class="modify-war">
						<view class="changepwd" v-show="flag=='pwd'">
							<input type="text" maxlength="16" v-model="oldPwd" placeholder="输入旧密码">
							<input type="text" maxlength="16" v-model="content" placeholder="输入新密码">
						</view>
						<view class="modify-main" v-show="flag!='pwd'">
							<textarea maxlength="24" placeholder="输入修改内容" v-model="content"></textarea>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import imageCropper from '../../components/ling-imgcropper/ling-imgcropper.vue'
	import util from '../../commons/js/util'
	import {
		RuntimeServerUrl
	} from "../../commons/getRuntimeEnv.js"
	import previewImg from "../../components/kxj-previewImage/kxj-previewImage.vue"
	import TopBar from "../../components/top-bar/top-bar.vue"
	import {
		deleteFriendApi
	} from '../../api/userinfo'
	export default {
		data() {
			const currentDate = this.getDate({
				format: true,
			})
			return {
				date: currentDate,
				sexOption: ['默认', '男', '女'],
				// 性别默认选项
				index: 0,
				//是否处于编辑状态
				editable: false,

				//编辑文本
				content: '',

				//修改文本标记
				flag: '',
				//旧密码
				oldPwd: '',
				userDetail: {},

				isModify: false,
				// cover缓出动画
				coverAnimationTemp: {},

				//头像裁剪
				tempFilePath: "",
				cropFilePath: "",
				isfriend: true

			}
		},
		components: {
			imageCropper,
			previewImg,
			TopBar
		},
		onLoad(option) {
			//传递过来的参数，向对应的账号发送好友申请
			// console.log(option,'detail'); 
			this.userid = uni.getStorageSync("userid")
			//如果是用户本身 则使用缓存文件
			this.userInfo = uni.getStorageSync("userInfo")
			this.obtainuserDetail(option)
			// console.log(this.date);
			this.hasRalation(option.id)

		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		watch: {
			isModify(pre, next) {
				// console.log('改变了',pre,next);
				if (pre) {
					this.coverAnimation()
				} else {
					this.coverAnimation()
				}
			}
		},
		methods: {
			back() {
				uni.navigateBack()
			},
			//显示修改密码的页面只能是 登入者的页面
			//比较本地的userid和token 方法不严谨
			isMaster() {
				if (this.userDetail.id == this.userid) {
					return true
				} else {
					return false
				}

			},
			hasRalation(fid) {
				// console.log(fid);
				util.request({
					url: '/search/isfriend',
					method: "POST",
					data: {
						uid: uni.getStorageSync('userid'),
						fid,
					}
				}).then(res => {
					// console.log(res.data.status,'shihaoyou');
					if (res.data.status == 200) {
						this.isfriend = true
					} else {
						this.isfriend = false
					}
				})
			},
			//返回上一层
			tab_cancel() {
				uni.navigateBack()
			},
			//通过用户id获取用户数据
			obtainuserDetail({
				id
			}) {
				// console.log('获取用户id',id);
				util.request({
					url: '/user/detail',
					method: "POST",
					data: {
						id,
					}
				}).then(res => {
					// this.date='2022-01-01'
					// console.log(this.date,'date');
					let {
						explain,
						time,
						birth,
						name,
						sex,
						phone,
						email,
						imgrul
					} = res.data.result
					// console.log(res.data.result,"用户详情未处理数据");
					// 生日默认是没有的
					let temp = {
						id,
						birth,
						time: new Date(time).getFullYear() + '年' + (new Date(time).getMonth() + 1) + '月' +
							new Date(time).getDate() + '日',
						explain,
						name,
						sex,
						phone,
						email,
						imgrul
					}
					if (birth == undefined) {
						// console.log(birth);
					} else {
						let month = (new Date(birth).getMonth() + 1).toString().padStart(2, '0')
						let day = (new Date(birth).getDate()).toString().padStart(2, '0')

						this.date = new Date(birth).getFullYear() + '-' + month + '-' + day
					}
					this.cropFilePath = `${RuntimeServerUrl}${imgrul}`
					// console.log(this.cropFilePath,'this.cropFilePath');
					if (temp.sex == "asexual") {
						this.index = 0
					} else if (temp.sex == "man") {
						this.index = 1;
					} else if (temp.sex == "female") {
						this.index = 2
					}
					// console.log(temp,'res.data.result');
					this.userDetail = temp;
					// console.log(this.userDetail);
				})
				//获取到用户id搜索到对应数据，赋值给this.userDetail
			},

			// 点击修改文字的动画


			// picker逻辑 添加点击修改时间的函数
			//点击修改index默认选项
			bindPickerChange: function(e) {
				let temp = ''
				if (e.detail.value == 0) {
					temp = 'asexual'
				} else if (e.detail.value == 1) {
					temp = 'man'
				} else if (e.detail.value == 2) {
					temp = 'female'
				} else {
					temp = 'asexual'
				}
				// console.log(temp);
				console.log('picker发送选择改变，携带值为')
				this.updateProfile('sex', temp, 'sex')
				this.index = e.detail.value
			},
			bindDateChange: function(e) {
				let date = new Date(e.detail.value)
				this.updateProfile('birth', date, 'birth')
				// console.log(date.getTime(),'date');
				this.$nextTick(() => {
					let month = (new Date(date).getMonth() + 1) < 10 ? '0' + (new Date(date).getMonth() + 1) :
						(new Date(date).getMonth() + 1)
					let day = (new Date(date).getDate()) < 10 ? '0' + (new Date(date).getDate()) : (new Date(
						date).getDate())
					// console.log(month,day);
					this.date = new Date(date).getFullYear() + '-' + month + '-' + day
				})
			},
			bindTimeChange: function(e) {
				this.time = e.detail.value
			},
			getDate(type) {
				const date = new Date(1990, 1, 1);
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 20;
				} else if (type === 'end') {
					year = year + 40;
				}
				month = month.toString().padStart(2, '0');
				day = month.toString().padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			//退出登入 情况userid和token
			loginOut(e) {
				uni.removeStorageSync("userid")
				uni.removeStorageSync("userInfo")
				uni.removeStorageSync("token")
				uni.showToast({
					title: "退出成功",
					icon: 'none',
					duration: 800,
				})
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/login/login?out=1'
					})
				}, 500)
				this.$socket.close()
			},
			//删除好友 需要传入 uid fid,此页面的userDetail信息是具体某人id的信息
			delFriens(fid) {
				uni.showModal({
					title: '提示',
					content: '这是一个模态弹窗',
					success: async function(res) {
						if (res.confirm) {
							let uid = uni.getStorageSync('userid')
							let {
								data
							} = await deleteFriendApi(uid, fid)
							console.log(data, "data");
							if (data.status == 200) {
								//更新
								uni.showToast({
									title: "删除成功",
									icon: "none",
									duration: 800,
								})
								await setTimeout(() => {
									uni.navigateTo({
										url: '/pages/index/index'
									})
								}, 500)
							} else {
								uni.showToast({
									title: "删除失败！",
									icon: "none",
									duration: 800,
								})
							}

						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});


			},
			//修改逻辑函数实现
			//@params {type:'修改类型'，data:'修改数据'，pwd：'修改密码'}
			updateProfile(type, data, kind, pwd = '') {

				//用于检查格式，格式正确为1
				let trigger = 0;
				//提示文字
				let hint = ""

				//是邮箱 并且邮箱格式正确，trigger=1 发送请求
				if (type == 'email') {
					util.checkEmailFormat(data) ? (trigger = 1) : hint = "邮箱格式不正确"
				} else if (type == 'phone') {
					//是手机号码 并且检查手机号码为真 trgger=1
					if (data == '') {
						trigger = 1
					} else
						util.checkPhoneNumberFormat(data) ? trigger = 1 : hint = "手机号码格式错误"
				} else if (type == 'explain') {
					//签名 可以为空
					data.length <= 60 ? trigger = 1 : hint = "签名长度小于60"
				} else if (type == 'name') {
					//昵称修改
					data.length > 0 && data.length <= 10 ? trigger = 1 : hint = "名称长度0-8"
				} else if (type == 'sex') {
					//性别修改
					if (['asexual', 'man', 'female'].includes(data));
					trigger = 1;
				} else if (type == 'birth') {
					//性别修改
					// console.log(data);
					trigger = 1;
				} else if (type == 'psw') {
					// console.log(type,data,pwd,'arguments');
					util.request({
						url: '/user/detailupdata',
						method: "POST",
						data: {
							id: this.userDetail.id,
							type,
							data,
							pwd,
						}
					}).then(res => {
						console.log(type, "type");
						// 修改密码没有加密，草
						// console.log(res,'修改密码是否执行了');
						if (res.data.status == 200) {
							// console.log('密码修改成功');
							uni.showToast({
								title: "成功，返回登入",
								icon: 'none',
								duration: 1500,
							})
							setTimeout(() => {
								uni.redirectTo({
									url: `/pages/login/login?email=${this.userDetail.email}`
								})
							}, 1000)
						} else {
							uni.showToast({
								title: "服务器错误",
								icon: 'none',
								duration: 2000
							})
						}
					})
					return;
				}
				// console.log(kind,'kind');
				trigger && util.request({
					url: '/user/detailupdata',
					method: "POST",
					data: {
						id: this.userDetail.id,
						type,
						data,
					}
				}).then(res => {
					this.updateLocalStorage()
					if (res.data.status == 200) {
						this.userDetail[kind] = data
						// uni.navigateBack(0)
					} else {
						uni.showToast({
							title: "服务器错误",
							icon: 'none',
							duration: 2000
						})
					}
				})

				trigger || uni.showToast({
					title: hint,
					icon: "error",
					duration: 1000
				})
			},
			//修改文字提交按钮
			submit() {
				this.isModify = false
				//需要修改对应的数据
				switch (this.flag) {
					case 'name':
						// 确定修改 后台数据
						// console.log(this.userDetail.id,'dsgfadgdfs')
						this.updateProfile('name', this.content, 'name')
						break;
					case 'explain':
						// console.log('explain')
						this.updateProfile('explain', this.content, 'explain')
						// this.userDetail.explain=this.content
						break;
					case 'phone':
						// 手机号码检查
						this.updateProfile('phone', this.content, 'phone')
						break;
					case 'email':
						//邮箱的检查

						this.updateProfile('email', this.content, 'email')
						break;
					case 'pwd':
						// console.log('psw',this.content,'psw',this.oldPwd)
						this.updateProfile('psw', this.content, 'psw', this.oldPwd)
						//执行旧密码验证逻辑，之后才会提交修改后的密码
						//使用登入的方法，已知用户邮箱
						// console.log(this.verityPwd(),'mima');
						//用户的this.userDetail.email this.content
						// this.verityPwd().then(res=>{
						// 	if(res){
						// 		// 修改成功
						// 		// this.updateProfile('pwd',this.content,'pwd')
						// 		console.log(this.content);
						// 		if(this.content.length<6){
						// 			uni.showToast({
						// 				title:"密码6~18",
						// 				icon:"none",
						// 				duration:1000
						// 			})									
						// 		}else{
						// 			this.updateProfile('pwd',this.content,'pwd')
						// 		}
						// 	}else{
						// 		// 修改失败
						// 		uni.showToast({
						// 			title:"旧密码不匹配",
						// 			icon:"none",
						// 			duration:1000
						// 		})
						// 	}
						// })
						break;
				}
			},
			verityPwd() {
				let result = util.request({
						url: '/signin/match',
						method: 'post',
						data: {
							data: this.userDetail.email,
							pwd: this.oldPwd
						}
					})
					.then(res => {
						// console.log(res,"res");
						//登入成功
						if (res.data.status == 200) {
							return true
						} else {
							return false
						}
					}).catch(err => {
						console.log(err);

					})
				return result
			},
			cancelEdit() {
				this.isModify = false
			},
			//type动画类型 add remove
			coverAnimation() {
				if (this.isMaster()) {
					var animation = uni.createAnimation({
						duration: 500,
						timingFunction: 'ease',
					})
					if (this.isModify) {
						this.animation = animation
						animation.bottom(0).step()
						this.coverAnimationTemp = animation.export()

					} else {
						this.animation = animation
						animation.bottom().step()
						this.coverAnimationTemp = animation.export()
					}
				}
			},
			//点击修改文字，跳出负一屏修改，并执行动画
			dataInteraction(value) {
				if (this.isMaster()) {
					this.isModify = true
					// console.log('queding');
					this.content = ''
					//通过target.getAttribute()获取通过value判断修改的是谁的数据
					switch (value) {
						case 'name':
							this.content = this.userDetail.name
							this.flag = value;
							break;
						case 'explain':
							this.content = this.userDetail.explain
							this.flag = value;
							break;
						case 'phone':
							this.content = this.userDetail.phone
							this.flag = value;
							break;
						case 'email':
							this.content = this.userDetail.email
							this.flag = value;
							break;
						case 'pwd':
							this.content = ''
							this.flag = value;
							break;
					}
				}
			},
			cover() {
				// console.log('cover');
			},
			preview() {
				uni.previewImage({
					urls: [this.cropFilePath],
					longPressActions: {
						itemList: ['修改头像', '保存图片'],
						success: (data) => {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
							if (data.tapIndex == 0) {
								uni.closePreviewImage()
								this.upload()
							} else if (data.tapIndex == 1) {
								uni.closePreviewImage()
								uni.saveImageToPhotosAlbum({
									filePath: this.cropFilePath,
									success: function() {
										uni.showToast({
											title: "保存成功",
											icon: 'none',
											duration: 1500,
										})
									}
								});
							}
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				})
			},
			//裁剪动画 上传
			upload() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ["album"], //从相册选择
					success: (res) => {
						//得到了图片内存中的资源URL
						this.tempFilePath = res.tempFilePaths[0];
						// console.log(this.tempFilePath,'tempFilePath');
					},
				});
			},
			confirm(e) {
				console.log(e, this.tempFilePath, 'cropFilePath');
				this.tempFilePath = "";
				this.cropFilePath = e.detail.tempFilePath;
				console.log("修改头像", this.cropFilePath);
				// console.log(e.detail.tempFilePath,'e.detail');
				uni.uploadFile({
					url: RuntimeServerUrl + '/upload/upload',
					// 文件路径
					filePath: e.detail.tempFilePath,
					name: 'file',
					header: {
						"Authorization": 'Bearer ' + uni.getStorageSync('token'),
					},
					// 携带数据请求体
					formData: {
						url: 'user',
						id: this.userDetail.id
					},
					success: (uploadFileRes) => {
						this.updateLocalStorage()
					}
				})
			},
			updateLocalStorage() {
				util.request({
					url: "/user/detail",
					method: "POST",
					data: {
						id: this.userid
					}
				}).then(res => {
					console.log("请求成功", res);
					//存用户详情星系 如果有数据就不用去发请求
					let userInfo = Object.assign({}, res.data.result, {
						imgrul: RuntimeServerUrl + res.data.result.imgrul
					})
					uni.setStorageSync("userInfo", userInfo)
					this.userProfile = RuntimeServerUrl + res.data.result.imgrul
				})
			},
			cancel() {
				// console.log("canceled");
				this.tempFilePath = "";
			},
		}
	}
</script>

<style lang="scss">
	.contianer {
		padding-top: 88rpx;
		/* #ifdef APP-PLUS */
		padding-top: calc(var(--status-bar-height)*2);
		/* #endif */
	}

	.main {
		height: 90%;
		padding: 50rpx 30rpx 20rpx 30rpx;

		.img {
			height: 150rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			// border-bottom: 1rpx solid red;
			.title {
				width: 10%;
				height: 50rpx;
				font-size: 32rpx;
				color: #272832;
				font-weight: 600;
			}

			.img_img {
				width: 80%;

				.img_image {
					height: 100rpx;
					width: 100rpx;
					border-radius: 20rpx;
				}
			}

			.edit {
				text-align: right;
				// padding-right: 10rpx;
				width: 5%;
				// border: 1rpx solid red;
				// height: 100%;
				line-height: 150rpx;

				image {
					transform: rotate(180deg);
					width: 20rpx;
					height: 20rpx;
				}
			}
		}

		.text {
			height: 100rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			// border-bottom: 1rpx solid red;
			.text_title {
				width: 10%;
				height: 50rpx;
				font-size: 32rpx;
				color: #272832;
				font-weight: 600;
			}

			.text_content {
				width: 80%;
				height: 48rpx;
				font-size: 32rpx;
				color: rgba(39, 40, 50, 0.60);
				letter-spacing: -0.55rpx;
				font-weight: 400;

				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 1;
				overflow: hidden;
			}

			.text_edit {
				text-align: right;
				// padding-right: 10rpx;
				width: 5%;
				// border: 1rpx solid red;
				// height: 100%;
				line-height: 150rpx;

				image {
					transform: rotate(180deg);
					width: 20rpx;
					height: 20rpx;
				}
			}
		}

		.exit {
			// margin-top: 100rpx;
			width: 90%;
			height: 80rpx;
			border-radius: 10rpx;
			margin: 70rpx auto;

			.exit_txt {

				text-align: center;
				font-size: 32rpx;
				color: #FF5D5B;
				// letter-spacing: -0.55px;
				line-height: 80rpx;
				font-weight: 400;
			}
		}

	}

	.modify {
		position: fixed;
		bottom: 0px;
		height: 100%;
		width: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 100;

		.cover {
			background-color: #fff;
			position: absolute;
			//coverAnimation
			bottom: -400rpx;
			width: 100%;
			height: 35%;

			.modify-top-bar {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 0 30rpx;

				view {
					font-size: 36rpx;
					font-weight: 600;
					line-height: 88rpx;
					height: 88rpx;
					// border: 1px solid;
				}

				.one {}

				.two {
					color: rgba(0, 0, 255, 0.5)
				}
			}

			.changepwd {
				margin: 0 auto;
				box-sizing: border-box;
				padding: 20rpx 30rpx;
				width: 90%;
				border-radius: 20rpx;
				background-color: rgba(232, 232, 232, 0.6);
				margin-bottom: 10rpx;

				input {
					padding: 10px;
				}
			}

			.modify-main {
				margin: 0 auto;
				padding: 20rpx 30rpx;
				box-sizing: border-box;
				width: 90%;
				border-radius: 20rpx;
				background-color: rgba(232, 232, 232, 0.6);

				textarea {
					width: 620rpx;
					height: 300rpx;
					font-size: 38rpx;
				}
			}
		}
	}
</style>